import subprocess
import glob
import os

host = "192.168.20.10"
ext = ".mp4"
video1_info = "30 "
video2_info = "60 "
video3_info = "90 "
local_cache = "/home/lv_ubuntu/Downloads/"
startup_file_name = "startup.txt"
emulator_file_name = "emulator.txt"
total_video = 3


#Xoa het cac file lien quan da ton tai

proc=subprocess.Popen(['rm','-rf',startup_file_name])
proc.communicate()

proc=subprocess.Popen(['rm','-rf',emulator_file_name])
proc.communicate()

#xoa het cac file mp4, do co dau * nen khong dung duoc Popen
cm = local_cache+ "*.mp4"
for fl in glob.glob(cm):
    os.remove(fl)

f = open(emulator_file_name,"w")
f.write("#Video_length Avg_start_up_time_no_use_method  Avg_start_up_time_use_method\n")
f.write(video1_info)

for i in xrange(1,total_video+1):
	f_sum = 0
	#Chay 10 lan cac video
	for j in xrange(0,5):
		video_file ="atomcaching:http://"+host+ "/video"+ str(i)+ext 
		proc=subprocess.Popen(['ffplay',video_file])
		proc.communicate()
		
		
		cm = local_cache+ "video"+str(i)+"-1"+ext
		proc=subprocess.Popen(['rm','-rf',cm])
		proc.communicate()
		
	# Doc file startup.txt de lay thoi gian bat dau trung binh
	f1 = open(startup_file_name,"r")
	for k in xrange(0,5):
		s = float(f1.readline())
		f_sum = f_sum + s
	f1.close()
	
	proc=subprocess.Popen(['rm','-rf',startup_file_name ])
	proc.communicate()
	
	#Lan cuoi cung chay de muc dich lay file atom_header de do khi co plugin
	video_file ="atomcaching:http://"+host + "/video"+ str(i)+ext 
	proc=subprocess.Popen(['ffplay',video_file])
	proc.communicate()	
	# Xoa bo file startup.txt nay vi khong can thiet
	proc=subprocess.Popen(['rm','-rf',startup_file_name ])
	proc.communicate()
	# Sau buoc nay caching da co tren client
	#Ghi thoi gian start up trung binh ra file emulator.txt
	f.write(""+str(f_sum/5)+" ")
	# Trong truong hop da co caching
	for j in xrange(0,5):
		video_file ="atomcaching:http://"+host +"/video"+ str(i)+ext 
		proc=subprocess.Popen(['ffplay',video_file])
		proc.communicate()
	f_sum = 0
	# Doc file startup.txt de lay thoi gian bat dau trung binh
	f1 = open(startup_file_name ,"r")
	for k in xrange(0,5):
		s = float(f1.readline())
		f_sum = f_sum + s
	f1.close()
	f.write(""+str(f_sum/5)+"\n")
	# sau khi do dac xong lan dau
	if i==1:
		f.write(video2_info)
	if i==2:
		f.write(video3_info)
	#Xoa het cac file lien quan da ton tai

	proc=subprocess.Popen(['rm','-rf',startup_file_name])
	proc.communicate()


	#xoa het cac file mp4, do co dau * nen khong dung duoc Popen
	cm = local_cache+ "*.mp4"
	for fl in glob.glob(cm):
	    os.remove(fl)
f.close()
